<template>
  <el-dialog
    class="dialog-box"
    v-model="dialogVisible"
    :title="!dialogParam.title ? '弹出框' : dialogParam.title"
    :destroy-on-close="true"
    width="1000px"
    :before-close="beforeClose"
    :closeOnClickModal="false"
    :closeOnPressEscape="false"
    @close="handleCancel"
  >
    <div>
      <div>
        <div class="relative">
          <div class="absolute right-0">
            <span v-if="selectData.length > 0">
              已关联{{ selectData.length }}份
            </span>
            <span v-if="selectData.length == 0">未关联合同</span>
          </div>
          <el-form
            ref="form"
            :model="formData"
            :rules="formRules"
            label-width="130px"
          >
            <el-row :gutter="80">
              <el-col :span="24">
                <el-form-item label="合同文件">
                  <el-upload
                    class="upload-demo"
                    action="#"
                    :before-upload="beforeAvatarUpload"
                    :http-request="requestFile"
                    :accept="uploadType['contract'].toString()"
                    :show-file-list="false"
                  >
                    <el-button type="default" style="font-size: 14px"
                      ><el-icon><UploadFilled /></el-icon>上传合同</el-button
                    >
                    <template #tip>
                      <div class="el-upload__tip float-right">
                        {{
                          `支持格式${uploadType[
                            'contract'
                          ].toString()} ，单个文件不能超过20MB`
                        }}
                      </div>
                    </template>
                  </el-upload>
                  <div class="text-14px mt-10px" style="width: 100%">
                    <div v-for="item in fileList" :key="item.fileId">
                      {{ item.origFileName }}
                      <!-- <a
                        :href="item.url"
                        target="_blank"
                        class="text-#409eff"
                        >{{ item.origFileName }}</a
                      > -->
                    </div>
                  </div>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="备注内容" prop="contractRemark">
                  <el-input
                    v-model="formData.contractRemark"
                    placeholder="请输入备注内容"
                    clearable
                    type="textarea"
                    :rows="3"
                    show-word-limit
                    maxlength="100"
                    style="width: 100%"
                  >
                  </el-input>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </div>
        <div>
          <el-table
            v-loading="loading"
            :data="listData"
            row-key="rcId"
            stripe
            ref="refTable"
          >
            <!-- @row-click="clickRow" -->
            <el-table-column type="expand" width="60">
              <template #default="props">
                <div v-if="props.row.fileList">
                  <el-table
                    v-if="props.row.fileList && props.row.fileList.length > 0"
                    :data="props.row.fileList"
                    @row-dblclick="(row, column, event) => viewFiles(row.url)"
                    row-class-name="cursor-pointer"
                  >
                    <el-table-column
                      type="index"
                      label="序号"
                      width="60"
                      align="center"
                    />
                    <el-table-column
                      label="文件名称"
                      prop="origFileName"
                      min-width="180"
                    >
                      <template #default="scope">
                        <div class="text-left">
                          {{ scope.row.origFileName }}
                        </div>
                      </template>
                    </el-table-column>
                    <el-table-column
                      label="操作"
                      align="center"
                      width="100"
                      fixed="right"
                      class-name="small-padding"
                    >
                      <template #default="scope">
                        <el-button
                          icon="View"
                          type="success"
                          plain
                          size="small"
                          @click="viewFiles(scope.row.url)"
                        >
                          <div>预览</div>
                        </el-button>
                      </template>
                    </el-table-column>
                  </el-table>
                  <div v-else>
                    <el-empty
                      :image-size="50"
                      description="该合同无附件"
                      class="p-y-3"
                    />
                  </div>
                </div>
              </template>
            </el-table-column>
            <el-table-column
              prop="contractName"
              label="合同名称"
              min-width="180"
            >
              <!-- <template #default="scope">
                <div class="text-left">{{ scope.row.contractName }}</div>
              </template> -->
            </el-table-column>
            <el-table-column prop="createBy" label="创建人员" width="100">
            </el-table-column>
            <el-table-column
              prop="createTime"
              label="创建时间"
              width="180"
              align="center"
            >
            </el-table-column>
            <el-table-column
              prop="createTime"
              label="附件数量"
              width="80"
              align="center"
            >
              <template #default="scope">
                <div
                  v-if="
                    scope.row.fileList && typeof scope.row.fileList == 'object'
                  "
                >
                  {{ scope.row.fileList.length }}
                </div>
                <div v-else>0</div>
              </template>
            </el-table-column>
            <el-table-column
              label="操作"
              align="center"
              width="260"
              fixed="right"
              class-name="small-padding"
            >
              <template #default="scope">
                <el-button
                  icon="SuccessFilled"
                  type="primary"
                  plain
                  size="small"
                  v-if="rowCalss(scope.row) == 'true'"
                  @click="clickRow(scope.row)"
                >
                  <div>已关联</div>
                </el-button>
                <el-button
                  icon="RemoveFilled"
                  v-else
                  type="danger"
                  plain
                  size="small"
                  @click="clickRow(scope.row)"
                >
                  <div>未关联</div>
                </el-button>
                <el-button
                  icon="View"
                  type="success"
                  plain
                  size="small"
                  @click="expandFile(scope.row)"
                >
                  <div>查看</div>
                </el-button>
                <el-button
                  plain
                  size="small"
                  type="success"
                  icon="DeleteFilled"
                  v-hasPermi="['qualityManage:contract:supervision']"
                  @click="handleDel(scope.row)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>

      <pagination
        class="relative"
        v-show="total > 5"
        :total="total"
        :autoScroll="false"
        :page-sizes="[5, 10, 15, 20]"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
      />
    </div>
    <template #footer>
      <span class="dialog-footer">
        <!-- <el-button @click="beforeClose">取消</el-button> -->
        <el-button type="primary" @click="handleAffirm"> 保存 </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup name="SelectContract">
import { getCurrentInstance } from 'vue'

import { strToArr, viewFile } from '@/utils/commo'
import {
  uploadFile,
  contractInfoSave,
  contractInfoListNoPriv,
  contractInfoDelete
} from '@/api/salesManage/contractManage'
import useUserStore from '@/store/modules/user'
const userStore = useUserStore()
const { proxy } = getCurrentInstance()

const uploadType = {
  contract: ['.rar', '.zip', '.doc', '.docx', '.pdf', '.jpg', '.png']
}

// 接受父级传递的参数
const props = defineProps({
  dialogParam: {
    required: true,
    type: Object || Array,
    default: () => {
      return {}
    }
  }
})

// 选中的数据
const selectData = ref([])
// 弹出框传入的参数
const dialogOpt = ref({
  multiple: true
})
// 弹出框是否隐藏
const dialogVisible = ref(false)
const data = reactive({
  queryParams: {
    pageNum: 1,
    pageSize: 5
  },
  loading: false,
  total: 0,
  listData: [],
  formData: {
    contractList: [], //关联合同
    contractRemark: '' //备注
  },
  formRules: {
    title: [
      {
        required: true,
        message: '请输入订单标题',
        trigger: 'blur'
      }
    ]
  },
  fileList: [],
  addBtn: false
})
let {
  queryParams,
  loading,
  total,
  listData,
  formData,
  formRules,
  fileList,
  addBtn
} = toRefs(data)

// 初始化
watch(
  () => props.dialogParam,
  () => {
    console.log('初始化===》', props.dialogParam)
    dialogVisible.value = props.dialogParam.open // 表单弹出框
    dialogOpt.value = {
      ...dialogOpt.value,
      ...props.dialogParam,
      open: undefined
    }
    formData.value = props.dialogParam.initData
      ? { ...props.dialogParam.initData }
      : {} //表单弹窗初始数据
    queryParams.value = {
      ...queryParams.value,
      ...props.dialogParam.queryParams //合同列表请求参数
    }
    selectData.value = formData.value.contractList
      ? [...formData.value.contractList]
      : []
    getList()
    // let { customerName, customerId, deptName, deptId, receiptsDate } =
    //   props.dialogParam.initData
    addBtn =
      props.dialogParam.initData?.customerName &&
      props.dialogParam.initData?.customerId &&
      props.dialogParam.initData?.deptName &&
      props.dialogParam.initData?.deptId &&
      props.dialogParam.initData?.receiptsDate
  },
  {
    // flush: 'post'
    immediate: true,
    deep: true
  }
)

/* 获取列表 */
function getList() {
  loading.value = true
  return new Promise((resolve, reject) => {
    contractInfoListNoPriv(queryParams.value).then(res => {
      loading.value = false
      if (res.code !== 200) return
      listData.value = res.data.records
      total.value = res.data.total
      resolve(res)
      // console.log(res, 'res')
    })
  })
}

// 展开附件下拉
function expandFile(row) {
  proxy.$refs.refTable.toggleRowExpansion(row)
}

// 点击行
function clickRow(row) {
  let select = selectData.value.filter(e => e.rcId == row.rcId) //判断点击的数据是否在列表中
  if (select.length == 0 && !dialogOpt.value.multiple) {
    // proxy
    //   .$confirm('是否关联该合同?', '警告', {
    //     confirmButtonText: '确定',
    //     cancelButtonText: '取消',
    //     type: 'warning'
    //   })
    //   .then(function () {
    //     selectData.value[0] = row
    //   })
    //   .catch(() => {})
    selectData.value[0] = row
  } else if (select.length == 0 && dialogOpt.value.multiple) {
    // proxy
    //   .$confirm('是否关联该合同?', '警告', {
    //     confirmButtonText: '确定',
    //     cancelButtonText: '取消',
    //     type: 'warning'
    //   })
    //   .then(function () {
    //     selectData.value.push(row)
    //   })
    //   .catch(() => {})

    selectData.value.push(row)
  } else if (select.length != 0) {
    proxy
      .$confirm('是否取消关联该合同?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
      .then(function () {
        let selectIndex = ''
        selectData.value.forEach((e, i) => {
          if (e.rcId == row.rcId) {
            selectIndex = i
          }
        })
        selectData.value.splice(selectIndex, 1)
      })
      .catch(() => {})
  }
  // console.log('点击==>', selectData.value)
}

// 选中行样式
const rowCalss = row => {
  let select = selectData.value.filter(e => e.rcId == row.rcId)
  return select.length > 0 ? 'true' : 'false'
}
// const rowCalss = computed(() => {
//   return function (row) {
//     let select = selectData.value.filter(e => e.rcId == row.rcId)
//     return select.length > 0 ? 'true' : 'false'
//   }
// })

const emit = defineEmits(['ok', 'close'])
// 确认操作
const handleAffirm = () => {
  let sData = [...selectData.value]
  if (sData.length == 0 && !formData.value.contractRemark) {
    return proxy.$message.error('当前未关联合同，请关联合同！')
  }
  emit('ok', {
    ...props.dialogParam,
    selectData: sData,
    formData: { ...formData.value, contractList: sData },
    dialogVisible: false
  })
  reset()
}
const beforeClose = () => {
  proxy
    .$confirm('当前关联的合同还未保存，是否保存?', '警告', {
      confirmButtonText: '保存',
      cancelButtonText: '不保存',
      closeOnClickModal: false,
      closeOnPressEscape: false,
      type: 'warning'
    })
    .then(function () {
      handleAffirm()
    })
    .catch(() => {
      handleCancel()
    })
}
// 取消操作
const handleCancel = () => {
  fileList.value = []
  reset()
  emit('close')
}
const reset = () => {
  dialogVisible.value = false
  formData.value = {}
  proxy.resetForm('form')
}

/**文件上传 限制条件
 *
 * @param {*} rawFile
 */
function beforeAvatarUpload(rawFile) {
  const ext = rawFile.name.substring(rawFile.name.lastIndexOf('.'))
  const allowType = uploadType['contract'].indexOf(ext) > -1
  const isLt2M = rawFile.size / 1024 / 1024 < 20

  if (!allowType) {
    proxy.$message.error(
      `上传文件只能是${uploadType['contract']
        .toString()
        .replace(/\./g, '')
        .replace(/,/g, '、')}格式!`
    )
  } else if (!isLt2M) {
    proxy.$message.error('上传文件大小不能超过 20MB!')
  }
  return allowType && isLt2M
}
// 上传文件
function requestFile(params) {
  let uploadData = new FormData()
  uploadData.append('file', params.file)
  uploadFile(uploadData).then(res => {
    if (res.code === 200) {
      fileList.value[0] = res.data
      addContract()
      // console.log('res==>', res)
      // proxy.$modal.msgSuccess(`${res.data.origFileName}上传成功`)
    }
  })
}
// 新增合同
function addContract() {
  let param = {
    partyaSig: props.dialogParam.initData.customerName, //甲方签约人
    partya: props.dialogParam.initData.customerId, //合同甲方
    partyaName: props.dialogParam.initData.customerName, //合同甲方名称
    partybSig: props.dialogParam.initData.deptName, //乙方签约人
    partyb: props.dialogParam.initData.deptId, //合同乙方
    partybName: props.dialogParam.initData.deptName, //合同乙方名称
    contractName: `${
      props.dialogParam.initData.customerName
    }的${fileList.value.map(e => e.fileName)}`, //props.dialogParam.initData.title, //合同名称
    contractAttribute: '1', //合同属性
    uploadType: props.dialogParam.initData.uploadType == '代理记账' ? null : 1, //上传方式
    businessType: '0', //业务属性
    businessCategorize: props.dialogParam.initData.businessType, //业务分类
    sinTime: props.dialogParam.initData.receiptsDate, //签订时间
    pbAlonePay: '2', //履约保证金是否单独支付
    fileNames: fileList.value.map(e => e.fileName), //合同文件
    contractSum: props.dialogParam.initData.contractSum, //合同金额
    contractTimeBegin: props.dialogParam.initData.contractTimeBegin, //合同时间起
    contractTimeEnd: props.dialogParam.initData.contractTimeEnd //合同时间止
  }
  contractInfoSave(param).then(res => {
    let fileId = res.data
    proxy.$modal.msgSuccess('合同上传成功')
    getList().then(res => {
      res.data.records.forEach(item => {
        if (item.rcId == fileId) {
          clickRow(item)
        }
      })
    })
  })
}

const handleDel = row => {
  proxy.$modal
    .confirm('是否确认删除?', '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    .then(() => {
      contractInfoDelete(row.rcId).then(res => {
        if (res.code === 200) {
          proxy.$modal.msgSuccess(res.data)
        }
        getList()
      })
    })
}

// 预览文件
function viewFiles(url) {
  viewFile(url, userStore.userInfo.nickName)
}

function init() {
  getList()
}
init()
</script>
<style lang="scss" scoped>
.dialog-box {
  .el-card {
    :deep(.el-card__body) {
      position: relative;
      overflow: hidden;
      padding: 0 !important;

      .suggest-tag {
        position: absolute;
        right: -30px;
        top: 10px;
        padding-left: 40px;
        padding-right: 40px;
      }
    }
  }
}
</style>
<style lang="scss">
.dialog-box {
  .el-dialog__body {
    padding-bottom: 10px !important;
  }
}
</style>
